<template>
  <div class="login-container">
    <div class="login-box">
      <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="ruleForm"
        status-icon
        :rules="rules"
        class="demo-ruleForm"
      >
        <el-form-item prop="username">
          <el-input
            v-model="ruleForm.username"
            placeholder="用户名"
            type="text"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="ruleForm.password"
            type="password"
            placeholder="密码"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item prop="captcha">
          <el-input
            class="captcha-input"
            v-model="ruleForm.captcha"
            type="text"
            placeholder="验证码"
            autocomplete="off"
          />
          <div class="captcha" ref="captchaDiv">
            <!-- {{ captchaPath }} -->
            <!-- <img class="captcha-img" :src="captchaPath" alt="验证码" /> -->
          </div>
        </el-form-item>
        <el-form-item>
          <el-button class="login-btn" type="primary" @click="loginForm()"
            >登录</el-button
          >
          <!-- <el-button @click="registeredForm()">注册</el-button> -->
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, toRefs } from 'vue'
import { useStore } from 'vuex'
import Cookie from 'js-cookie'
import { useRouter } from 'vue-router'

import { adminLoginApi, getAdminCaptcha } from '@/request/login/loginApi.ts'
import { key } from '@/store'

const state = reactive({
  ruleForm: {
    username: 'admin',
    password: '123456',
    captcha: '5d0n',
    // username: '',
    // password: '',
    // captcha: '',
  },
  captchaText: '',
  captchaPath: '',
})

const captchaDiv = ref<HTMLDivElement>()

const { ruleForm, captchaText, captchaPath } = toRefs(state)

const ruleFormRef = ref()
const router = useRouter()
const store = useStore(key)

const validatePassword = (
  rule: unknown,
  value: string | undefined,
  callback: (msg?: string) => void
) => {
  if (!value) {
    callback('密码不能为空')
    return
  }
  callback()
}

const validateCaptcha = (
  rule: unknown,
  value: string | undefined,
  callback: (msg?: string) => void
) => {
  if (!value) {
    callback('验证码不能为空')
    return
  }
  if (value.length !== 4) {
    callback('验证码长度必须为4位')
    return
  }
  if (value.toLowerCase() !== captchaText.value.toLowerCase()) {
    callback('验证码错误')
    return
  }
  callback()
}

const rules = reactive({
  username: [{ required: true, message: '用户名不能为空!', trigger: 'blur' }],
  password: [{ validator: validatePassword, trigger: 'blur' }],
  captcha: [{ validator: validateCaptcha, trigger: 'blur' }],
})

const loginForm = async () => {
  try {
    await ruleFormRef.value.validate()
    console.log('校验通过')
    let res = await adminLoginApi(ruleForm.value)
    console.log(res)

    if (res.code === 200) {
      Cookie.set('Authorization', `${res.data.tokenHead} ${res.data.token}`, {
        expires: 1,
      })
      store.dispatch('getAdminInfo')
      router.replace('/index')
    }
  } catch (error) {
    console.log('校验不通过', error)
  }
}

const getCaptcha = async () => {
  const data = await getAdminCaptcha()

  captchaText.value = data.data.captcha.text

  // 正式时注释掉这行
  ruleForm.value.captcha = data.data.captcha.text

  captchaPath.value = data.data.captcha.data

  captchaDiv.value!.innerHTML = captchaPath.value
}

onMounted(async () => {
  await getCaptcha()
})

const registeredForm = () => {}
</script>

<style lang="less" scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100vw;
  height: 100vh;
  background-color: #2d3a4a;
  .login-box {
    width: 400px;
    height: 300px;
    .captcha-input {
      flex: 1;
      margin-right: 20px;
    }
    .captcha {
      width: 100px;
      height: 34px;
      border-radius: 4px;
      overflow: hidden;
    }
    .login-btn {
      width: 100%;
    }
  }
}
</style>
